package org.shop.weixin.util;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.shop.weixin.http.HttpClientConnectionManager;
import org.shop.weixin.pojo.WxBill;
import org.shop.weixin.pojo.WxBillLog;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;










public class GetWxOrderno
{
  public static DefaultHttpClient httpclient;

  static
  {
    httpclient = new DefaultHttpClient();
    httpclient = (DefaultHttpClient)HttpClientConnectionManager.getSSLInstance(httpclient);
  }


  public static String getPayNo(String url,String xmlParam){
	  System.out.println("xml是:"+xmlParam);
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String prepay_id = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	     Map<String, Object> dataMap = new HashMap<String, Object>();
	     System.out.println("json是:"+jsonStr);

	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return prepay_id;
	    }
	    Map map = doXMLParse(jsonStr);
	    String return_code  = (String) map.get("return_code");
	    prepay_id  = (String) map.get("prepay_id");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return prepay_id;
  }
  /**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}

			m.put(k, v);
		}

		//关闭流
		in.close();

		return m;
	}
	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}
  public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param  strxml
	 * @return
	 * @throws  JDOMException
	 * @throws  IOException
	 */
	public static Map<String,String> doXMLParse2(String strxml) throws JDOMException, IOException {
	if(null == strxml || "".equals(strxml)) {
	return null;
	}
	Map<String,String> m = new HashMap<String,String>();
	InputStream in =String2Inputstream(strxml);
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(in);
	Element root = doc.getRootElement();
	List list = root.getChildren();
	Iterator it = list.iterator();
	while(it.hasNext()) {
	Element e = (Element) it.next();
	String k = e.getName();
	String v = "";
	List children = e.getChildren();
	if(children.isEmpty()) {
	v = e.getTextNormalize();
	} else {
	v = getChildrenText(children);
	}
	m.put(k, v);
	}
	//关闭流
	in.close();
	return m;
	}

	public static Map doXML(String url, String xmlParam) {
		DefaultHttpClient httpclient;
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager
				.getSSLInstance(httpclient);
		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
				true);
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
		Map map=new HashMap();
		try {
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils
					.toString(response.getEntity(), "UTF-8");
			System.out.println(jsonStr);
			map = doXMLParse2(jsonStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public static Map doWxBillText(String url, String xmlParam) {
		DefaultHttpClient httpclient;
		httpclient = new DefaultHttpClient();
		httpclient = (DefaultHttpClient) HttpClientConnectionManager
				.getSSLInstance(httpclient);
		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,
				true);
		HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
		 Set<WxBill> WxBillList = new HashSet<WxBill>();
		Map map = new HashMap();
		try {
			httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
			HttpResponse response = httpclient.execute(httpost);
			String jsonStr = EntityUtils
					.toString(response.getEntity(), "UTF-8");
			int rowNumber = 0;
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new ByteArrayInputStream(jsonStr.getBytes())));
			String str;
			while ((str = br.readLine()) != null) {
				rowNumber++;

				if (str.startsWith("`20")) {
					String str1 = str.replaceAll("`", "");
					System.out.println(str1);
					String[] wxorder = str1.split(",");
					WxBill wxBill =new WxBill(wxorder[0],wxorder[1],wxorder[2],wxorder[3],wxorder[4],wxorder[5],wxorder[6],
							wxorder[7],wxorder[8],wxorder[9],wxorder[10],wxorder[11],wxorder[12],wxorder[13],wxorder[14],wxorder[15],
							wxorder[16],wxorder[17],wxorder[18],wxorder[19],wxorder[20],wxorder[21],wxorder[22],wxorder[23]);

					WxBillList.add(wxBill);

				}else{
					if (!str.startsWith("总交易单数") && !str.startsWith("交易时间")) {
						System.out.println("总交易单数说明："+str);
						String str2 = str.replaceAll("`", "");
						String[] billLog = str2.split(",");
						WxBillLog bill = new WxBillLog(billLog[0],billLog[1],billLog[2],billLog[3],billLog[4]);
						map.put("bill", bill);
					}
				}

			}


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		map.put("wxOrderList", WxBillList);
		return map;
	}
}